EMA and MACD with Trailing Stop Loss (by Coinrule)An exponential moving average ( EMA ) is a type of moving average (MA) that places a greater weight and significance on the most recent data points. The exponential moving average is also referred to as the exponentially weighted moving average. An exponentially weighted moving average reacts more significantly to recent price changes than a simple moving average simple moving average ( SMA ), which applies an equal weight to all observations in the period.
Moving average convergence divergence ( MACD ) is a trend-following momentum indicator that shows the relationship between two moving averages of a security’s price. The MACD is calculated by subtracting the 26-period exponential moving average ( EMA ) from the 12-period EMA.
The result of that calculation is the MACD line. A nine-day EMA of the MACD called the "signal line," is then plotted on top of the MACD line, which can function as a trigger for buy and sell signals. Traders may buy the security when the MACD crosses above its signal line and sell—or short—the security when the MACD crosses below the signal line. Moving average convergence divergence ( MACD ) indicators can be interpreted in several ways, but the more common methods are crossovers, divergences, and rapid rises/falls.
The Strategy enters and closes the trade when the following conditions are met:
LONG
The MACD histogram turns bearish
EMA7 is greater than EMA14
EXIT
Price increases 3% trailing
Price decreases 1% trailing
This strategy is back-tested from 1 January 2022 to simulate how the strategy would work in a bear market and provides good returns.
Pairs that produce very strong results include XRPUSDT on the 1-minute timeframe. This short timeframe means that this strategy opens and closes trades regularly
In order to further improve the strategy, the EMA can be changed from 7 and 14 to, say, EMA20 and EMA50. Furthermore, the trailing stop loss can also be changed to ideally suit the user to match their needs.
The strategy assumes each order is using 30% of the available coins to make the results more realistic and to simulate you only ran this strategy on 30% of your holdings. A trading fee of 0.1% is also taken into account and is aligned to the base fee applied on Binance.
Recherche dans les scripts pour "stop loss"
Oversold RSI with Tight Stop-Loss Strategy (by Coinrule)KRAKEN:LINKUSD
This is one of the best strategies that can be used to get familiar with technical indicators and start to include them in your rules on Coinrule .
ENTRY
1. This trading system uses the RSI (Relative Strength Index) to anticipate good points to enter positions. RSI is a technical indicator frequently used in trading. It works by measuring the speed and change of price movements to determine whether a coin is oversold (indicating a good entry point) or overbought (indicating a point of exit/entry for a short position). The RSI oscillates between 0 and 100 and is traditionally considered overbought when over 70 and oversold when below 30.
2. To pick the right moment to buy, the strategy enters a trade when the RSI falls below 30 indicating the coin is oversold and primed for a trend reversal.
EXIT
The strategy then exits the position when the price appreciates 7% from the point of entry. The position also maintains a tight stop-loss and closes the position if the price depreciates 1% from the entry price. The idea behind this is to cut your losing trades fast and let your winners ride.
The best time frame for this strategy based on our back testing data is the daily. Shorter time frames can also work well on certain coins, however in our experience, the daily works best. Feel free to experiment with this script and test it on a variety of your coins! With our back testing data a trading fee of 0.1% is taken into account. The fee is aligned to the base fee applied on Binance, which is the largest cryptocurrency exchange by volume. In the example shown, this strategy made a handsome net profit of 52.6% on Chainlink with 66.67% of trades being profitable.
You can execute this strategy on your favorite exchanges with Coinrule .
isamuch - 2MA Cross and Stop Lossสัญญาณซื้อ/ขาย : มาจาก Moving Average สองเส้นตัดกัน
Stop Loss : มาจากราคาต่ำสุด/สูงสุดของช่วงระหว่าง Moving Average สองเส้นตัดกันก่อนหน้ากับ Moving Average ตัดกันปัจจุบัน
Parabolic SAR Strategy With take profit and stop lossDo not make it too difficult!
This is my first strategy! I took the Parabolic SAR Strategy and added Stop Loss and Take profit, and I can see some fantastic results in 2h-3h-4h on some of the Crypto coins.
This is for training only, and I do not recommend using it as part of a trading bot, however, I do myself.
MultiPrice AlertThis is an alert script using Pinescript version 4. This enables one to set 5 alerts (1 StopLoss, 4 Targets), on 3 different symbols, at using a single alert in the UI.
Every visible line will only appear on the symbols that are selected. After setting targets when making an alert, select this indicator as a condition. Change the name to whatever you want, usually the names of the set of tickers.
The Alert message is dyanmic showing which Symbol with each type of alert, at whatever price.
Ability to disable the targets + symbols.
Alerts work by Stop Loss crossing under price and Targets Cross Over. Enabling the "Short" Targets reverses this.
The line that is being displayed is actually the price of the asset being moved over x number of bars. I have not found a way to plot a traditional horizontal line, as the code for it uses a fixed price.
As it being a user input, it is a variable. Any help with this would be appreicated.
Alerts are set to once per bar.
Known bug that sometimes if the prices that you set are inside the current candle stick, then your alert will immeaditally fire, either change the timeframe or let it fire and wait fo
After a target is hit, I reccomend setting the alert to 0 and REMAKING the alert. You MUST REMAKE THE ALERT AFTER ANY CHANGES. This script WILL NOT CHANGE ALERTS AS YOU CHANGE SETTINGS.
TradingView Alerts are not this smart , at least I haven't found a way to do this yet.
Anti-Volume Stop Loss multi timeframe [LM]Hello Traders,
I would like to introduce you fork of popular indicator Anti-Volume Stop Loss created by Buff Dormeier and cracked here on tradingview by @Rafka so shout out to him. I have tried to crack it myself as well as I'm big fan of Dormeier's work but it's not easy so really big thanks to Rafka
I have refactored original script and have included multi timeframe setting.
As its shown below you can select higher timeframe to track lower one:
Enjoy!
Bitlinc MARSI Study AST w/ Take Profit & Stop loss - beta 0.1This script is beta 0.1 - will update as soon as the script is tradable
This script is based on AST on a 10 minute timeframe. You can change the asset and the timeframe for any asset you want to trade, but for it to work correct ALL settings have to be testes in the Strategy section of the TradingView. Each assets and timeframe require a different mixture of settings. This is NOT a one settings fits all trading for all assets on any timeframe. Below are the settings and explanation on how it works.
How it fires a buy / sell:
The script will plot an RSI with upper and lower bands in a separate indicator window. The idea behind this script is to fire a LONG when MA crosses OVER lower band and fire a SHORT when the MA crosses under the lower band. Each order that fires is an OCO (Order Cancels Order) for pyramiding.
Settings:
You have full control of these settings as mentioned above, you must configure every part of this script for each asset and timeframe you trade.
- Length of MA
- Length
- Upper bands of RSI
- Lower bands of RSI
- Take profit percentage
- Stop loss percentage
- Month to start and end the strategy (within 2020)
- Day to start and end the strategy (within 2020)
- Quantity type
- Slippage
- Pyramiding
***Remember that after the signal to enter or exit a trade is fired, the alert will trigger AFTER the close of the candle that caused the tigger to fire
ATR Stop Loss LONG/SHORT by melihgulerYou can monitor the stop loss level according to ATR in 2 ways (Long/Short).
RSI + EMA+ MTF Stop-LossThis is a simple RSI with multiple MTF (No security) to help with direction short and long-term.
The rsi for the current chart has a noise reduction, while the rest are based on ma's.
I have supplied an extra flexible mtf rsi ma for potential adjustable/long-term stop-loss or direction identification.
Enjoy
RSI Stop LossExperiment for using RSI as a stop loss value, shows where the price will be when the RSI increases or decreases by a specified amount.
poki buy and sell Take profit and stop lossThis indicator is based on modelius model of lazy bear weis model with ATR for the buy=B sell =S
in addition there is Take profit and stop loss in % both for short and for long
next stage is to know the resistance level and support based on bollinger marked in blue and red dots
Also included Parabolic Sar (blue and red dots rising up or down)
The color of bulish or bearish zone is based on the cross of Hull avreage and linear regression ( for each time set may need different setting for accuracy )
So how to use this scrupt to better profit
1. if you have B signal and its on lower support level then its good starting place for buy. look at the Parabolic Sar if its in agreement. The exit can be either by S =sell, Take profit that you decide on % or by end of Parabolic SAR upward
2. exact the oposite for short
Play with setting for the desired results or change modify this script for your purpose
Pivot Stop LossHere we intend to use pivot points for stop loss and take profit. This has the added benefit of helping you to visualize support and resistance levels.
Hull modelius take profit and stop lossThis model has Hull moving average, fibs in form of Bollinger ,SMA and Modelius model with ATR for buy and sell power based on weis volume. Inside alerts for buy and sell. take profit and stop loss for both longs and shorts
so have fun
SL + TP Dynamics - By M.LolasStop Loss e Take Profit dinâmicos para operações semiautomatizadas.
By M.Lolas
STOP-LOSS-RSI with Edge-Preserving Filter Strategy V2Modified RSI strategy with entry and exit points.
I have allowed for High and Low risk for anyone interested in using it (NO GUARANTEES. DO YOUR OWN RESEARCH).
I will later consider incorporating the standard RSI for exit points. I am sure returns will increase based on current test runs :)
Returns look good based on the strategy result.
Bullish Engulfing at Daily Support (Pivot Low) - R Target (v6)1. What this strategy really is (in human terms)
This strategy is not about predicting the market.
It’s about waiting for proof that buyers are stepping in at a price where they already should.
Think of it like this:
“I only buy when price falls into a known ‘floor’ and buyers visibly take control.”
That’s it.
Everything in the script enforces that idea.
2. The two ingredients (nothing else)
Ingredient #1: Daily Support (the location)
Support is an area where price previously fell and then reversed upward.
In the script:
Support is defined as the most recent confirmed daily swing low
A swing low means:
Price went down
Stopped
Then went up enough to prove that buyers defended that level
This matters because:
You’re not guessing where support might be
You’re using a level where buyers already proved themselves
“At support” doesn’t mean exact
Markets don’t bounce off perfect lines.
So the script allows a small zone (the “support tolerance”):
Example: 0.5% tolerance
If support is at 100
Anywhere between ~99.5–100.5 counts
This prevents missing good trades just because price was off by a few ticks.
Ingredient #2: Bullish Engulfing Candle (the trigger)
This is the confirmation.
A bullish engulfing candle means:
Sellers were in control
Buyers stepped in hard enough to fully overpower them
The bullish candle’s body “swallows” the previous candle
Psychologically, it says:
“Sellers tried, failed, and buyers just took control.”
That’s why this candle works only at support.
A bullish engulfing in the middle of nowhere means nothing.
3. Why daily timeframe matters
The daily chart:
Filters out noise
Reflects decisions made by institutions, not random scalpers
Produces fewer but higher-quality signals
That’s why:
The script uses daily data
You typically get very few trades per month
Most days: no trade
That “boredom” is the edge.
4. When a trade is taken (exact conditions)
A trade happens only if ALL are true:
Price drops into a recent daily support zone
A bullish engulfing candle forms on the daily chart
Risk is clearly defined (entry, stop, target)
If any one is missing → no trade
5. How risk is controlled (this is crucial)
The stop loss (where you admit you’re wrong)
The stop is placed:
Below the support level
Or below the low of the engulfing candle
With a small ATR buffer so normal noise doesn’t stop you out
Meaning:
“If price breaks below this area, buyers were wrong. I’m out.”
No hoping. No moving stops. No exceptions.
Position sizing (why this strategy survives losing streaks)
Each trade risks a fixed % of your account (default 1%).
So:
Big stop = smaller position
Small stop = larger position
This keeps every trade equal in risk, not equal in size.
That’s professional behavior.
6. The take-profit logic (why 2.8R matters)
Instead of guessing targets:
The strategy uses a multiple of risk (R)
Example:
Risk = $1
Target = $2.80
You can lose many times and still come out ahead.
This is why:
Win rate ≈ 60% is more than enough
Even 40–45% could still work if discipline is perfect
7. Why patience is the real edge (not the pattern)
The bullish engulfing is common.
Bullish engulfing at daily support is rare.
Most people fail because they:
Trade engulfings everywhere
Ignore location
Lower standards when bored
Add “just one more indicator”
Your edge is:
Saying no 95% of the time
Taking only trades that look obvious after they work
8. How to use this strategy effectively (rules to follow)
Rule 1: Only take “clean” setups
Skip trades when:
Support is messy or unclear
Price is chopping sideways
The engulfing candle is tiny
The market is news-chaotic (earnings, FOMC, etc.)
If you have to convince yourself, skip it.
Rule 2: One trade at a time
This strategy works best when:
You’re not stacked in multiple correlated trades
You treat each setup like it matters
Quality > quantity.
Rule 3: Journal screenshots, not just numbers
After each trade, save:
Daily chart screenshot
Support level marked
Entry / stop / target
After 50–100 trades, patterns jump out:
Best tolerance %
Best stop buffer
Markets that behave well vs poorly
That’s how the original trader refined it.
Rule 4: Expect boredom and drawdowns
You will have:
Weeks with zero trades
Clusters of losses
Long flat periods
That’s normal.
If you “fix” it by adding more trades:
You destroy the edge.
9. Who this strategy is perfect for
This fits you if:
You don’t want screen addiction
You prefer process over excitement
You’re okay being wrong often
You want something you can execute for years
It is not for:
Scalpers
Indicator collectors
People who need action every day
10. The mindset shift (the real lesson of that story)
The money didn’t come from bullish engulfings.
It came from:
Defining one repeatable behavior
Removing everything else
Trusting math + patience
Doing nothing most of the time
If you want, next we can:
Walk through real example trades bar-by-bar
Optimize settings for a specific market you trade
Add filters that increase quality without adding complexity
MDZ Strategy v4.2 - Multi-factor trend strategyWhat This Strategy Does
MDZ (Momentum Divergence Zones) v4.2 is a trend-following strategy that enters long positions when multiple momentum and trend indicators align. It's designed for swing trading on higher timeframes (2H-4H) and uses ATR-based position management.
The strategy waits for strong trend confirmation before entry, requiring agreement across five different filters. This reduces trade frequency but aims to improve signal quality.
Entry Logic
A long entry triggers when ALL of the following conditions are true:
1. EMA Stack (Trend Structure)
Price > EMA 20 > EMA 50 > EMA 200
This "stacked" alignment indicates a strong established uptrend
2. RSI Filter (Momentum Window)
RSI between 45-75 (default)
Confirms momentum without entering overbought territory
3. ADX Filter (Trend Strength)
ADX > 20 (default)
Ensures the trend has sufficient strength, not a ranging market
4. MACD Confirmation
MACD line above signal line
Histogram increasing (momentum accelerating)
5. Directional Movement
+DI > -DI
Confirms bullish directional pressure
Exit Logic
Positions are managed with ATR-based levels:
ParameterDefaultDescriptionStop Loss2.5 × ATRBelow entry priceTake Profit6.0 × ATRAbove entry priceTrailing Stop2.0 × ATROptional, activates after entry
The default configuration produces a 1:2.4 risk-reward ratio.
Presets
The strategy includes optimized presets based on historical testing:
PresetTimeframeNotes1H Standard1 HourMore frequent signals2H Low DD2 HourConservative settings3H Optimized3 HourBalanced approach4H Swing4 HourWider stops for swing tradesCustomAnyFull manual control
Select "Custom" to adjust all parameters manually.
Inputs Explained
EMAs
Fast EMA (20): Short-term trend
Slow EMA (50): Medium-term trend
Trend EMA (200): Long-term trend filter
RSI
Length: Lookback period (default 14)
Min/Max: Entry window to avoid extremes
ADX
Min ADX: Minimum trend strength threshold
Risk
Stop Loss ATR: Multiplier for stop distance
Take Profit ATR: Multiplier for target distance
Trail ATR: Trailing stop distance (if enabled)
Session (Optional)
Filter entries by time of day
Recommended OFF for 3H+ timeframes
What's Displayed
Info Panel (Top Right)
Current preset
Trend status (Strong/Wait)
ADX, RSI, MACD readings
Position status
Risk-reward ratio
Stats Panel (Top Left)
Net P&L %
Total trades
Win rate
Profit factor
Maximum drawdown
Chart
EMA lines (20 blue, 50 orange, 200 purple)
Green background during strong uptrend
Triangle markers on entry signals
Important Notes
⚠️ This is a long-only strategy. It does not take short positions.
⚠️ Historical results do not guarantee future performance. Backtests show what would have happened in the past under specific conditions. Markets change, and any strategy can experience drawdowns or extended losing periods.
⚠️ Risk management is your responsibility. The default settings risk 100% of equity per trade for backtesting purposes. In live trading, appropriate position sizing based on your risk tolerance is essential.
⚠️ Slippage and commissions matter. The backtest includes 0.02% commission and 1 tick slippage, but actual execution costs vary by broker and market conditions.
Best Practices
Test on your specific market — Results vary significantly across different instruments
Use appropriate position sizing — Never risk more than you can afford to lose
Combine with your own analysis — No indicator replaces understanding market context
Paper trade first — Validate the strategy matches your trading style before risking capital
Alerts
Two alerts are available:
MDZ Long Entry: Fires when all entry conditions are met
Uptrend Started: Fires when EMA stack first aligns bullish
Methodology
This strategy is based on the principle that trend continuation has better odds than reversal when multiple timeframe momentum indicators agree. By requiring five independent confirmations, it filters out weak setups at the cost of fewer total signals.
The ATR-based exits adapt to current volatility rather than using fixed pip/point targets, which helps the strategy adjust to different market conditions.
Questions? Leave a comment below.
[GYTS] VolatilityToolkit LibraryVolatilityToolkit Library
🌸 Part of GoemonYae Trading System (GYTS) 🌸
🌸 --------- INTRODUCTION --------- 🌸
💮 What Does This Library Contain?
VolatilityToolkit provides a comprehensive suite of volatility estimation functions derived from academic research in financial econometrics. Rather than relying on simplistic measures, this library implements range-based estimators that extract maximum information from OHLC data — delivering estimates that are 5–14× more efficient than traditional close-to-close methods.
The library spans the full volatility workflow: estimation, smoothing, and regime detection.
💮 Key Categories
• Range-Based Estimators — Parkinson, Garman-Klass, Rogers-Satchell, Yang-Zhang (academically-grounded variance estimators)
• Classical Measures — Close-to-Close, ATR, Chaikin Volatility (baseline and price-unit measures)
• Smoothing & Post-Processing — Asymmetric EWMA for differential decay rates
• Aggregation & Regime Detection — Multi-horizon blending, MTF aggregation, Volatility Burst Ratio
💮 Originality
To the best of our knowledge, no other TradingView script combines range-based estimators (Parkinson, Garman-Klass, Rogers-Satchell, Yang-Zhang), classical measures, and regime detection tools in a single package. Unlike typical volatility implementations that offer only a single method, this library:
• Implements four academically-grounded range-based estimators with proper mathematical foundations
• Handles drift bias and overnight gaps, issues that plague simpler estimators in trending markets
• Integrates with GYTS FiltersToolkit for advanced smoothing (10 filter types vs. typical SMA-only)
• Provides regime detection tools (Burst Ratio, MTF aggregation) for systematic strategy integration
• Standardises output units for seamless estimator comparison and swapping
🌸 --------- ADDED VALUE --------- 🌸
💮 Academic Rigour
Each estimator implements peer-reviewed methodologies with proper mathematical foundations. The library handles aspects that are easily missed, e.g. drift independence, overnight gap adjustment, and optimal weighting factors. All functions include guards against edge cases (division by zero, negative variance floors, warmup handling).
💮 Statistical Efficiency
Range-based estimators extract more information from the same data. Yang-Zhang achieves up to 14× the efficiency of close-to-close variance, meaning you can achieve the same estimation accuracy with far fewer bars — critical for adapting quickly to changing market conditions.
💮 Flexible Smoothing
All estimators support configurable smoothing via the GYTS FiltersToolkit integration. Choose from 10 filter types to balance responsiveness against noise reduction:
• Ultimate Smoother (2-Pole / 3-Pole) — Near-zero lag; the 3-pole variant is a GYTS design with tunable overshoot
• Super Smoother (2-Pole / 3-Pole) — Excellent noise reduction with minimal lag
• BiQuad — Second-order IIR filter with quality factor control
• ADXvma — Adaptive smoothing based on directional volatility
• MAMA — Cycle-adaptive moving average
• A2RMA — Adaptive autonomous recursive moving average
• SMA / EMA — Classical averages (SMA is default for most estimators)
Using Infinite Impulse Response (IIR) filters (e.g. Super Smoother, Ultimate Smoother) instead of SMA avoids the "drop-off artefact" where volatility readings crash when old spikes exit the window.
💮 Plug-and-Play Integration
Standardised output units (per-bar log-return volatility) make it trivial to swap estimators. The annualize() helper converts to yearly volatility with a single call. All functions work seamlessly with other GYTS components.
🌸 --------- RANGE-BASED ESTIMATORS --------- 🌸
These estimators utilise High, Low, Open, and Close prices to extract significantly more information about the underlying diffusion process than close-only methods.
💮 parkinson()
The Extreme Value Method -- approximately 5× more efficient than close-to-close, requiring about 80% less data for equivalent accuracy. Uses only the High-Low range, making it simple and robust.
• Assumption: Zero drift (random walk). May be biased in strongly trending markets.
• Best for: Quick volatility reads when drift is minimal.
• Parameters: smoothing_length (default 14), filter_type (default SMA), smoothing_factor (default 0.7)
Source: Parkinson, M. (1980). The Extreme Value Method for Estimating the Variance of the Rate of Return. Journal of Business, 53 (1), 61–65. DOI
💮 garman_klass()
Extends Parkinson by incorporating Open and Close prices, achieving approximately 7.4× efficiency over close-to-close. Implements the "practical" analytic estimator (σ̂²₅) which avoids cross-product terms whilst maintaining near-optimal efficiency.
• Assumption: Zero drift, continuous trading (no gaps).
• Best for: Markets with minimal overnight gaps and ranging conditions.
• Parameters: smoothing_length (default 14), filter_type (default SMA), smoothing_factor (default 0.7)
Source: Garman, M.B. & Klass, M.J. (1980). On the Estimation of Security Price Volatilities from Historical Data. Journal of Business, 53 (1), 67–78. DOI
💮 rogers_satchell()
The drift-independent estimator correctly isolates variance even in strongly trending markets where Parkinson and Garman-Klass become significantly biased. Uses the formula: ln(H/C)·ln(H/O) + ln(L/C)·ln(L/O).
• Key advantage: Unbiased regardless of trend direction or magnitude.
• Best for: Trending markets, crypto (24/7 trading with minimal gaps), general-purpose use.
• Parameters: smoothing_length (default 14), filter_type (default SMA), smoothing_factor (default 0.7)
Source: Rogers, L.C.G. & Satchell, S.E. (1991). Estimating Variance from High, Low and Closing Prices. Annals of Applied Probability, 1 (4), 504–512. DOI
💮 yang_zhang()
The minimum-variance composite estimator — both drift-independent AND gap-aware. Combines overnight returns, open-to-close returns, and the Rogers-Satchell component with optimal weighting to minimise estimator variance. Up to 14× more efficient than close-to-close.
• Parameters: lookback (default 14, minimum 2), alpha (default 1.34, optimised for equities).
• Best for: Equity markets with significant overnight gaps, highest-quality volatility estimation.
• Note: Unlike other estimators, Yang-Zhang does not support custom filter types — it uses rolling sample variance internally.
Source: Yang, D. & Zhang, Q. (2000). Drift-Independent Volatility Estimation Based on High, Low, Open, and Close Prices. Journal of Business, 73 (3), 477–491. DOI
🌸 --------- CLASSICAL MEASURES --------- 🌸
💮 close_to_close()
Classical sample variance of logarithmic returns. Provided primarily as a baseline benchmark — it is approximately 5–8× less efficient than range-based estimators, requiring proportionally more data for the same accuracy.
• Parameters: lookback (default 14), filter_type (default SMA), smoothing_factor (default 0.7)
• Use case: Comparison baseline, situations requiring strict methodological consistency with academic literature.
💮 atr()
Average True Range -- measures volatility in price units rather than log-returns. Directly interpretable for stop-loss placement (e.g., "2× ATR trailing stop") and handles gaps naturally via the True Range formula.
• Output: Price units (not comparable across different price levels).
• Parameters: smoothing_length (default 14), filter_type (default SMA), smoothing_factor (default 0.7)
• Best for: Position sizing, trailing stops, any application requiring volatility in currency terms.
Source: Wilder, J.W. (1978). New Concepts in Technical Trading Systems . Trend Research.
💮 chaikin_volatility()
Rate of Change of the smoothed trading range. Unlike level-based measures, Chaikin Volatility shows whether volatility is expanding or contracting relative to recent history.
• Output: Percentage change (oscillates around zero).
• Parameters: length (default 10), roc_length (default 10), filter_type (default EMA), smoothing_factor (default 0.7)
• Interpretation: High values suggest nervous, wide-ranging markets; low values indicate compression.
• Best for: Detecting volatility regime shifts, breakout anticipation.
🌸 --------- SMOOTHING & POST-PROCESSING --------- 🌸
💮 asymmetric_ewma()
Differential smoothing with separate alphas for rising versus falling volatility. Allows volatility to spike quickly (fast reaction to shocks) whilst decaying slowly (stability). Essential for trailing stops that should widen rapidly during turbulence but narrow gradually.
• Parameters: alpha_up (default 0.1), alpha_down (default 0.02).
• Note: Stateful function — call exactly once per bar.
💮 annualize()
Converts per-bar volatility to annualised volatility using the square-root-of-time rule: σ_annual = σ_bar × √(periods_per_year).
• Parameters: vol (series float), periods (default 252 for daily equity bars).
• Common values: 365 (crypto), 52 (weekly), 12 (monthly).
🌸 --------- AGGREGATION & REGIME DETECTION --------- 🌸
💮 weighted_horizon_volatility()
Blends volatility readings across short, medium, and long lookback horizons. Inspired by the Heterogeneous Autoregressive (HAR-RV) model's recognition that market participants operate on different time scales.
• Default horizons: 1-bar (short), 5-bar (medium), 22-bar (long).
• Default weights: 0.5, 0.3, 0.2.
• Note: This is a weighted trailing average, not a forecasting regression. For true HAR-RV forecasting, it would be required to fit regression coefficients.
Inspired by: Corsi, F. (2009). A Simple Approximate Long-Memory Model of Realized Volatility. Journal of Financial Econometrics .
💮 volatility_mtf()
Multi-timeframe aggregation for intraday charts. Combines base volatility with higher-timeframe (Daily, Weekly, Monthly) readings, automatically scaling HTF volatilities down to the current timeframe's magnitude using the square-root-of-time rule.
• Usage: Calculate HTF volatilities via request.security() externally, then pass to this function.
• Behaviour: Returns base volatility unchanged on Daily+ timeframes (MTF aggregation not applicable).
💮 volatility_burst_ratio()
Regime shift detector comparing short-term to long-term volatility.
• Parameters: short_period (default 8), long_period (default 50), filter_type (default Super Smoother 2-Pole), smoothing_factor (default 0.7)
• Interpretation: Ratio > 1.0 indicates expanding volatility; values > 1.5 often precede or accompany explosive breakouts.
• Best for: Filtering entries (e.g., "only enter if volatility is expanding"), dynamic risk adjustment, breakout confirmation.
🌸 --------- PRACTICAL USAGE NOTES --------- 🌸
💮 Choosing an Estimator
• Trending equities with gaps: yang_zhang() — handles both drift and overnight gaps optimally.
• Crypto (24/7 trading): rogers_satchell() — drift-independent without the lag of Yang-Zhang's multi-period window.
• Ranging markets: garman_klass() or parkinson() — simpler, no drift adjustment needed.
• Price-based stops: atr() — output in price units, directly usable for stop distances.
• Regime detection: Combine any estimator with volatility_burst_ratio().
💮 Output Units
All range-based estimators output per-bar volatility in log-return units (standard deviation). To convert to annualised percentage volatility (the convention in options and risk management), use:
vol_annual = annualize(yang_zhang(14), 252) // For daily bars
vol_percent = vol_annual * 100 // Express as percentage
💮 Smoothing Selection
The library integrates with FiltersToolkit for flexible smoothing. General guidance:
• SMA: Classical, statistically valid, but suffers from "drop-off" artefacts when spikes exit the window.
• Super Smoother / Ultimate Smoother / BiQuad: Natural decay, reduced lag — preferred for trading applications.
• MAMA / ADXvma / A2RMA: Adaptive smoothing, sometimes interesting for highly dynamic environments.
💮 Edge Cases and Limitations
• Flat candles: Guards prevent log(0) errors, but single-tick bars produce near-zero variance readings.
• Illiquid assets: Discretisation bias causes underestimation when ticks-per-bar is small. Use higher timeframes for more reliable estimates.
• Yang-Zhang minimum: Requires lookback ≥ 2 (enforced internally). Cannot produce instantaneous readings.
• Drift in Parkinson/GK: These estimators overestimate variance in trending conditions — switch to Rogers-Satchell or Yang-Zhang.
Note: This library is actively maintained. Suggestions for additional estimators or improvements are welcome.






















